package com.zc.microservice.user.core.app.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zc.auth.security.core.authentication.AuthenticationTokenService;
import com.zc.commons.lang.exception.MsgHandlerException;
import com.zc.commons.user.dto.AuthorizedUser;
import com.zc.commons.user.pojo.RoleInfo;
import com.zc.microservice.user.core.domain.pojo.LoginUser;
import com.zc.microservice.user.core.domain.pojo.RegistUser;
import com.zc.microservice.user.core.infra.entity.SystemRole;
import com.zc.microservice.user.core.infra.entity.TenantUser;
import com.zc.microservice.user.core.infra.mapper.SystemRoleMapper;
import com.zc.microservice.user.core.infra.mapper.TenantUserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 用户基础服务
 *
 * @author zcj
 * @version 1.0.0
 * @date 2022/1/24 10:24
 */
@Service
public class UserBaseService {

    @Autowired
    private TenantUserMapper userMapper;
    @Autowired
    private SystemRoleMapper systemRoleMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private AuthenticationTokenService tokenService;

    public AuthorizedUser doLogin(LoginUser loginUser) {
        LambdaQueryWrapper<TenantUser> query = Wrappers.lambdaQuery();
        query.eq(TenantUser::getAccount, loginUser.getAccount());

        TenantUser tenantUser = this.userMapper.selectOne(query);
        if (tenantUser == null) {
            throw new MsgHandlerException("用户不存在！");
        }
        boolean matched = passwordEncoder.matches(loginUser.getPassword(), tenantUser.getPassword());
        if (matched) {
            AuthorizedUser authorizedUser = new AuthorizedUser();
            BeanUtils.copyProperties(tenantUser, authorizedUser);
            List<SystemRole> roles = systemRoleMapper.queryRolesByUser(tenantUser.getId());
            List<RoleInfo> roleInfos = roles.stream().map(val -> {
                RoleInfo roleInfo = new RoleInfo();
                roleInfo.setId(val.getId());
                roleInfo.setCode(val.getRoleCode());
                roleInfo.setName(val.getRoleName());
                return roleInfo;
            }).collect(Collectors.toList());
            authorizedUser.setRoleInfos(roleInfos);
            // jwt
            // String token = jsonWebTokenService.generateJwtToken(authUser, false);
            // redis存储
            String uuid = UUID.randomUUID().toString();
            tokenService.saveToken(uuid, JSON.toJSONString(authorizedUser), 24 * 3600);
            //
            authorizedUser.setToken(uuid);

            return authorizedUser;
        }
        throw new MsgHandlerException("密码错误！");
    }

    /**
     * 注册用户
     *
     * @param registUser
     */
    public void doRegist(RegistUser registUser) {
        TenantUser tenantUser = new TenantUser();
        LambdaQueryWrapper<TenantUser> userQuery = Wrappers.lambdaQuery();
        userQuery.eq(TenantUser::getAccount, registUser.getAccount());
        TenantUser user = this.userMapper.selectOne(userQuery);
        if (user != null) {
            throw new MsgHandlerException("用户已存在！");
        }
        BeanUtils.copyProperties(registUser, tenantUser);
        tenantUser.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        String enPwd = passwordEncoder.encode(registUser.getPassword());
        tenantUser.setPassword(enPwd);
        tenantUser.setIsDeleted(Boolean.FALSE);
        tenantUser.setIsFrozen(Boolean.FALSE);

        this.userMapper.insert(tenantUser);
    }


}
